package top.codedance.iotp.iot.sdk;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.iot.sdk.entity.DistributedRegistyUris;
import top.codedance.iotp.loadblance.IotServerLoadBlance;
import top.codedance.iotp.loadblance.common.AlgorithmType;

public abstract class AbstractHttpDistributedService extends AbstractIotService {

    protected DistributedRegistyUris registyHosts;
    protected String deviceId = null;
    protected IotServerLoadBlance iotServerLoadBlance;
    protected String httpServerHost;
    protected int requestTimeout = -1;

    public AbstractHttpDistributedService(DistributedRegistyUris registyHosts, String deviceId) {
        this(registyHosts, deviceId, -1);
    }

    public AbstractHttpDistributedService(DistributedRegistyUris registyHosts, String deviceId, int requestTimeout) {
        this.registyHosts = registyHosts;
        this.deviceId = deviceId;
        this.iotServerLoadBlance = IotServerLoadBlance.getInstance(this.registyHosts);
        this.httpServerHost = this.iotServerLoadBlance.blanceHttp(this.deviceId);
        this.requestTimeout = requestTimeout;
    }

    public AbstractHttpDistributedService(DistributedRegistyUris registyHosts, AlgorithmType at, String deviceId) {
        this(registyHosts, at, deviceId, -1);
    }

    public AbstractHttpDistributedService(DistributedRegistyUris registyHosts, AlgorithmType at, String deviceId, int requestTimeout) {
        this.registyHosts = registyHosts;
        this.deviceId = deviceId;
        this.iotServerLoadBlance = IotServerLoadBlance.getInstance(this.registyHosts, at);
        this.httpServerHost = this.iotServerLoadBlance.blanceHttp(this.deviceId);
        this.requestTimeout = requestTimeout;
    }

    protected JSONObject request(String url, String params){
        if(this.httpServerHost != null) {
            if(this.deviceId != null) {
                JSONObject jsonObject = JSONObject.parseObject(params);
                jsonObject.put("deviceId", deviceId);
                params = jsonObject.toJSONString();
            }
            JSONObject post = HttpRequestUtil.post(this.httpServerHost + "/rest/api" + url, params);
            if(!post.containsKey("status") || post.getIntValue("status") != 200){
                this.httpServerHost = this.iotServerLoadBlance.reBlanceHttp(this.deviceId);
            }
            return reductionData(post);
        }else{
            this.httpServerHost = this.iotServerLoadBlance.reBlanceHttp(this.deviceId);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", 500);
            jsonObject.put("message", "load blance fail.");
            return jsonObject;
        }
    }
}
